package com.iot08.api.service;

import com.iot08.api.config.properties.ListDataProperties;
import com.iot08.api.service.active.DailyActiveService;
import com.iot08.api.service.active.MonthActiveService;
import com.iot08.api.service.active.WeekActiveService;
import com.iot08.api.vo.request.VersionReqVO;
import com.iot08.common.entity.app.Account;
import com.iot08.common.entity.app.VersionUpdates;
import com.iot08.common.entity.app.active.DailyActive;
import com.iot08.common.entity.app.active.MonthActive;
import com.iot08.common.entity.app.active.WeekActive;
import com.iot08.common.service.base.BaseService;
import com.iot08.common.utils.DateUtil;
import com.iot08.common.utils.StringUtil;
import com.iot08.common.utils.response.ResponseEnum;
import com.iot08.common.utils.response.ResponseMap;
import com.mongodb.client.FindIterable;
import com.mongodb.client.model.Filters;
import lombok.extern.slf4j.Slf4j;
import org.bson.Document;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

/**
 * @version 1.0
 * @Description:
 * @author: Rock
 * @time: 2021/1/4 15:04
 */
@Slf4j
@Service
public class VersionupdatesService extends BaseService<VersionUpdates> {

    @Resource
    private DailyActiveService dailyActiveService;
    @Resource
    private WeekActiveService weekActiveService;
    @Resource
    private MonthActiveService monthActiveService;

    @Resource
    private AccountService accountService;
    @Resource
    private ListDataProperties listDataProperties;

    /**
     * 上传版本号
     *
     * @param vo
     * @time: 2021/1/5 16:09
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap version(VersionReqVO vo) {
        if (StringUtil.isBlank(vo.getChannel())) {
            vo.setChannel("tx");
        }
        Account account = accountService.findById(vo.getOpenid());
        if (account == null) {
            log.error("Account is null. id={}. version vo={}", vo.getOpenid(), vo);
            return ResponseMap.fail(ResponseEnum.STATUS2000.getCode(), ResponseEnum.STATUS2000.getMsg());
        }
        Update updateAccount = new Update();
        boolean needUpdate = false;
        if (!vo.getChannel().equals(account.getChannel())) {
            updateAccount.set("channel", vo.getChannel());
            needUpdate = true;
        }
        String version = vo.getVersion();
        if (!version.equals(account.getVersion())) {
            updateAccount.set("version", version);
            needUpdate = true;
        }
        if(needUpdate){
            //更新操作
            accountService.updateById(vo.getOpenid(), updateAccount);
        }

        String uuid = vo.getUuid();
        if (uuid != null) {
            HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            //请求头数据解析处理
            String userAgent = req.getHeader("user-agent");
            //iOS 系统版本  默认还是支持VoIP 的
            String sysVersion = "";
            //手机型号
            String phoneType = "";
            // 手机类型 (目前只有 android 和 ios)
            String mobileType = "";
            String packageName = "";
            if (StringUtil.isNotBlank(userAgent)) {
                String[] sysInfoList = userAgent.split(";");
                String[] tempArr = sysInfoList[0].split("\\(");
                phoneType = tempArr[tempArr.length - 1];
                if (userAgent.contains("iOS")) {
                    //IOS User-Agent: watch/1.6.0 (iPhone; iOS 11.2.1; Scale/2.00)
                    packageName = req.getHeader("BundleId");
                    for (String value : sysInfoList) {
                        if (value != null && value.contains("iOS")) {
                            tempArr = value.split(" ");
                            sysVersion = tempArr[tempArr.length - 1];
                        }else if(value != null && value.contains(" (")){
                            //watch/1.6.0 (iPhone
                            String[] verSplit = value.split(" ")[0].split("/");
                            version = verSplit[verSplit.length - 1];
                        }
                    }
                    mobileType = "ios";
                } else if (userAgent.contains("Android")) {
                    packageName = req.getHeader("packageName");
                    //android User-Agent: swatch/1.6.0(SM-N9500;Android;9)
                    sysVersion = sysInfoList[sysInfoList.length - 1].replace(")", "");
                    tempArr = tempArr[0].split("/");
                    version = tempArr[tempArr.length - 1];
                    mobileType = "android";
                }
            }
            //======日活/周活/月活 的统计=====
            //创建时设置失效对应的失效时间 就不用定期去删除

            //daily_active 日活表
            long num = dailyActiveService.count(new Query().addCriteria(Criteria.where("_id").is(uuid)));
            if (num == 0) {
                DailyActive baseActive = new DailyActive();
                baseActive.setId(uuid);
                baseActive.setOpenid(vo.getOpenid());
                baseActive.setChannel(vo.getChannel());
                baseActive.setUuid(uuid);
                baseActive.setPhoneVersion(sysVersion);
                baseActive.setVersion(version);
                baseActive.setPackageName(packageName);
                baseActive.setMobileType(mobileType);
                baseActive.setPhoneType(phoneType);
                dailyActiveService.add(baseActive);
            }
            //week_active 周活表
            num = weekActiveService.count(new Query().addCriteria(Criteria.where("_id").is(uuid)));
            if (num == 0) {
                WeekActive baseActive = new WeekActive();
                baseActive.setId(uuid);
                baseActive.setOpenid(vo.getOpenid());
                baseActive.setChannel(vo.getChannel());
                baseActive.setUuid(uuid);
                baseActive.setPhoneVersion(sysVersion);
                baseActive.setVersion(version);
                baseActive.setPackageName(packageName);
                baseActive.setMobileType(mobileType);
                baseActive.setPhoneType(phoneType);
                weekActiveService.add(baseActive);
            }
            //month_active 月活表
            num = monthActiveService.count(new Query().addCriteria(Criteria.where("_id").is(uuid)));
            if (num == 0) {
                MonthActive baseActive = new MonthActive();
                baseActive.setId(uuid);
                baseActive.setOpenid(vo.getOpenid());
                baseActive.setChannel(vo.getChannel());
                baseActive.setUuid(uuid);
                baseActive.setPhoneVersion(sysVersion);
                baseActive.setVersion(version);
                baseActive.setPackageName(packageName);
                baseActive.setMobileType(mobileType);
                baseActive.setPhoneType(phoneType);
                monthActiveService.add(baseActive);
            }
        }

        ResponseMap res = ResponseMap.success();
        Document query = new Document();
        query.put("status", 1);
        //查询版本列表信息
        FindIterable<Document> documents = this.findDoc(query, Filters.eq("publishtime", -1), 0, 1);
        String content = "1、优化体验 \n";
        if (documents != null && documents.first() != null) {
            Document document = documents.first();
            if (document.containsKey("forceUpdate_status") && document.getInteger("forceUpdate_status") > 0) {
                res.put("forceUpdate", document.getInteger("forceUpdate_status"));
            } else {
                res.put("forceUpdate", 0);
            }
            if (document.get(vo.getChannel()) instanceof Document) {
                Document channelDoc = (Document) document.get(vo.getChannel());
                res.put("android_version", channelDoc.getOrDefault("version", ""));
                res.put("android_url", channelDoc.getOrDefault("url", ""));
                res.put("ios_version", channelDoc.getOrDefault("ios_version", ""));
                res.put("ios_url", channelDoc.getOrDefault("ios_url", ""));
                res.put("version_code", channelDoc.getOrDefault("version_code", ""));
                if (channelDoc.containsKey("android_content")) {
                    res.put("android_content", channelDoc.getString("android_content").replace("\\n", "\n"));
                }
                if (channelDoc.containsKey("ios_content")) {
                    res.put("ios_content", channelDoc.getString("ios_content").replace("\\n", "\n"));
                }
                if (channelDoc.containsKey("update_description")) {
                    res.put("content", channelDoc.getString("update_description").replace("\\n", "\n"));
                }
            }
        } else if (listDataProperties.getChannelMap() != null && listDataProperties.getChannelMap().containsKey(vo.getChannel())) {
            res.put("android_version", listDataProperties.getChannelMap().get(vo.getChannel()).get("android_version"));
            res.put("android_content", content);
            res.put("android_url", listDataProperties.getChannelMap().get(vo.getChannel()).get("android_url"));
            res.put("ios_version", listDataProperties.getChannelMap().get(vo.getChannel()).get("ios_version"));
            res.put("ios_url", listDataProperties.getChannelMap().get(vo.getChannel()).get("ios_url"));
            res.put("ios_content", content);
            res.put("content", content);
            res.put("forceUpdate", listDataProperties.getChannelMap().get(vo.getChannel()).get("forceUpdate"));
            res.put("version_code", listDataProperties.getChannelMap().get(vo.getChannel()).get("version_code"));
        }
        return res;
    }

    /**
     * 应用更新
     *
     * @param packageName
     * @param packageVersion
     * @param channel
     * @time: 2021/1/5 15:57
     * @author: Rock
     * @version 1.0
     */
    public ResponseMap getUpdateAndroid(String packageName, String packageVersion, String channel) {
        ResponseMap res = ResponseMap.success();
        channel = StringUtil.isBlank(channel) ? "tongxin" : channel;
        Document query = new Document();
        query.put("status", 1);
        FindIterable<Document> documents = this.findDoc(query, Filters.eq("publishtime", -1), 0, 1);
        if (documents != null && documents.first() != null) {
            Document document = documents.first();
            if (document.get(channel) instanceof Document) {
                res.put("version", ((Document) document.get(channel)).get("version"));
                res.put("apkURL", ((Document) document.get(channel)).get("url"));
                res.put("version_code", ((Document) document.get(channel)).get("version_code"));
                return res;
            }
        }
        if (listDataProperties != null && listDataProperties.getChannelMap() != null && listDataProperties.getChannelMap().containsKey(channel)) {
            res.put("version", listDataProperties.getChannelMap().get(channel).get("android_version"));
            res.put("apkURL", listDataProperties.getChannelMap().get(channel).get("android_url"));
            res.put("version_code", listDataProperties.getChannelMap().get(channel).get("version_code"));
        }
        return res;
    }
}
